-module(sctp_pair_server_sup).
-behaviour(supervisor).
-export([init/1]).
-export([start_link/0,start_child/1,dump_sctp_pairs/0]).

-export([forward/2]).
-define(SERVER,?MODULE).

forward({SIP,SPort,DIP,DPort},Packet_Tuple) ->
	Sctp_Pair =
		if
			(SIP > DIP) -> {SIP,SPort,DIP,DPort};
			true -> {DIP,DPort,SIP,SPort}
		end,
	Pid = case get(Sctp_Pair) of
		  undefined ->
			  {ok,Child_Id} = start_child(Sctp_Pair),
			  put(Sctp_Pair,Child_Id),
			  %%error_logger:info_msg("a sctp Pair server is start ~p for ~p",[get(Sctp_Pair),Sctp_Pair]),
			  Child_Id;
		  Res ->
			  Res
		  end,
	sctp_pair_server:handle(Pid,{packet_comming,Packet_Tuple}).

dump_sctp_pairs() ->
	io:format("sctp pair:~n~p~n",[get()]).

start_link() ->
	supervisor:start_link({local,?SERVER},?MODULE,[]).
init([]) ->
	Children = [
		{sctp_pair_server,{sctp_pair_server,start_link,[]},temporary,brutal_kill,worker,[sctp_pair_server]}
		],
	RestartStrategy = {simple_one_for_one,0,1},
	{ok,{RestartStrategy,Children}}.
start_child(Sctp_Pair) ->
	supervisor:start_child(?SERVER,[Sctp_Pair]).
